import sys
import os
from todomanager import TodoManager
from todomanager_http import TodomanagerWithHttp

# manager = TodoStorage()
manager = TodomanagerWithHttp("localhost:5000")


# manager.load()

def isRefresh(ch):
    return ch == '\x1b' or ch == 'r' or ch == 'R'


def isQuitKey(ch):
    return ch == 'q' or ch == 'Q'


def isCreateKey(ch):
    return ch == 'N' or ch == 'n'


def isMarkCompletedKey(ch):
    return ch == 'O' or ch == 'o'


def cls():
    os.system('cls' if os.name == 'nt' else 'clear')


def todo_list():
    print("待办事项\n==========")
    todos = manager.get_list()
    todos = [x for x in todos if not x.completed]

    if todos is None or len(todos) == 0:
        print("\n\n当前没有未完成的事项\n\n")
    else:
        print()
        for x in todos:
            print(f"{x.id}.\t {x.title}")
        print()

    print("N=创建事项, O=标记完成, ESC=刷新列表, Q=退出")


def clear_screen():
    pass


def create_todo():
    cls()
    print("创建待办事项\n==========\n")
    title = input("请输入事项内容（Enter=创建)：")
    if title.strip() == '':
        return
    else:
        manager.create(title)


def mark_completed():
    todo_id = input("输入事项ID以标记完成（Enter=标记完成)：")
    if todo_id.strip() == '':
        return
    else:
        manager.mark_completed(int(todo_id))


def start():
    while True:
        cls()
        todo_list()
        while True:
            ch = input("请输入命令：")
            if isQuitKey(ch):  # 退出
                sys.exit(0)
            elif isCreateKey(ch):  # 创建
                create_todo()
                break
            elif isMarkCompletedKey(ch):  # 标记为完成
                mark_completed()
                break
            elif isRefresh(ch):  # 刷新列表
                break


start()
